package game;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

/**
 * Timer Class to switch turns
 * 
 * @author Yasasvi
 */

public class Timers {
    private Timer timer;
    private int secondsLeft;
    private transient Round round;
    private transient Game currentGame;
    private transient GameDriver driver;

    public Timers(int foodRequirement, int playerFood, Round round,
	    Game currentGame, GameDriver driver) {
	this.timer = new Timer(1000, new TimerListener());
	this.currentGame = currentGame;
	this.round = round;
	this.driver = driver;
	this.secondsLeft = setSecondsLeft(playerFood, foodRequirement);
	
    }

    /**
     * Listener for Timer which sets the time in the label If timer ends then
     * goes to landSelection method in driver
     */
    class TimerListener implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent arg0) {
	    secondsLeft--;

	    round.getInfoPanel().setTimerLabel(secondsLeft);
	    round.getInfoPanel().repaint();

	    if (secondsLeft <= 0) {
		if (round.getRoundZeroCount() < currentGame.playerArraySize() * 2 - 1) {
		    round.setRoundZeroCount(round.getRoundZeroCount() + 1);
		    round.incrementPlayerInt();
		    round.landSelection();
		} else {
		    driver.toPanel(round.getMapPanel(), BorderLayout.CENTER);
		    round.incrementPlayerInt();
		    round.takeTurn();
		}
	    }
	}
    }

    /**
     * Sets number of seconds based on food requirements and how much food the
     * player currently has
     * 
     * @param playerFood
     * @param foodReq
     * @return number of Seconds
     */
    public int setSecondsLeft(int playerFood, int foodReq) {
	if (playerFood == 0)
	    return 5;
	else if (playerFood > 0 && playerFood < foodReq)
	    return currentGame.getTime() - 20;
	else
	    return currentGame.getTime();
    }

    public void setSecondsLeft(int secondsLeft) {
	this.secondsLeft = secondsLeft;
    }

    public int getSecondsLeft() {
	return secondsLeft;
    }

    public void start() {
	timer.start();
    }

    public void stop() {
	timer.stop();
    }
}
